const { Service } = require('egg');
const { tableToList } = require('../utils/tools');


module.exports = class PlanService extends Service {
  /**
   * 培养计划
   * @return {Array} *
   */
  async table() {
    const Cookie = this.ctx.state.Cookie;
    const apiUrl = `${this.ctx.state.baseUrl}/jsxsd/pyfa/pyfa_query`;
    const promiseList = [ this.ctx.curl(apiUrl, {
      method: 'GET',
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
    }), this.ctx.curl(`${this.ctx.state.baseUrl}/jsxsd/pyfa/topyfamx`, {
      method: 'GET',
      headers: {
        Cookie,
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
      },
    }) ];
    const [ res, res2 ] = await Promise.all(promiseList);

    const header = [ '课程名称', '属性', '性质', '学分', '考核方式', '学时', '开课院系' ]; // 列名称
    if (res.status === 200) {
      try {
        /* 因为培养计划中没有课程性质，因此在修读情况页中获取数据并构造一个课程编号-类型的字典 */
        const tableList2 = tableToList(res2.data.toString(), '#mxh');
        const typeId = {};
        let type = '';
        tableList2.forEach((item, idx) => {
          if (idx < 2) return true;
          if (item[0] === '合计') { return false; }
          if (item[0] === '小计') {
            type = '';
            return true;
          }
          if (type === '') {
            type = item[0];
          }
          typeId[item[2]] = type;
        });
        /* end */

        const tableList = tableToList(res.data.toString(), '#dataList');
        /* [ '序号', '开课学期', '课程编号', '课程名称', '开课单位', '学分', '总学时', '考核方式', '课程属性', '是否考试' ]; */

        const columnNeed = [ 3, 8, -1, 5, 7, 6, 4 ]; // 需要提取的列序号

        const info = {};
        for (let i = 1; i < tableList.length; i++) {
          const term = tableList[i][1];
          if ((term in info) === false) { info[term] = []; }
          const tem = [];
          columnNeed.forEach(idx => {
            if (idx === -1) tem.push(typeId[tableList[i][2]] || '');
            else tem.push(tableList[i][idx] || '');
          });
          info[term].push(tem);
        }
        return { table: info, header };

      } catch (err) {
        return err;
      }
    }
    return { table: {}, header };
  }

};
